package com.ryder.petmatediarybackend.module.auth.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.ryder.petmatediarybackend.common.response.Result;
import com.ryder.petmatediarybackend.module.auth.dto.LoginDTO;
import com.ryder.petmatediarybackend.module.auth.dto.RefreshTokenDTO;
import com.ryder.petmatediarybackend.module.auth.dto.RegisterDTO;
import com.ryder.petmatediarybackend.module.auth.service.AuthService;
import com.ryder.petmatediarybackend.module.auth.vo.LoginVO;
import com.ryder.petmatediarybackend.module.auth.vo.TokenVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

/**
 * 描述: 认证控制器（注册、登录、刷新、注销）
 *
 * @author Ryder
 * @version 1.0
 * @since 1.0
 * 更新日期: 2025/10/28
 */
@Slf4j
@Tag(name = "认证管理", description = "用户注册、登录、刷新、注销接口")
@RestController
@RequestMapping("/auth")
@RequiredArgsConstructor
public class AuthController {

    private final AuthService authService;

    @Operation(summary = "用户注册", description = "注册新用户账号，默认分配宠物主人角色，无需登录")
    @PostMapping("/register")
    public Result<String> register(@Valid @RequestBody RegisterDTO dto) {
        log.info("[用户注册] 执行注册, 方法=register, 用户名={}, 邮箱={}, 手机={}", 
                dto.getUsername(), dto.getEmail(), dto.getPhone());
        authService.register(dto);
        log.info("[用户注册] 注册成功, 用户名={}", dto.getUsername());
        return Result.ok("注册成功，请登录");
    }

    @Operation(summary = "用户登录", description = "用户名密码登录，返回 Access Token + Refresh Token + 用户信息，无需登录")
    @PostMapping("/login")
    public Result<LoginVO> login(@Valid @RequestBody LoginDTO dto, HttpServletRequest request) {
        log.info("[用户登录] 执行登录, 方法=login, 用户名={}, 设备类型={}, IP={}", 
                dto.getUsername(), dto.getDeviceType(), request.getRemoteAddr());
        LoginVO loginVO = authService.login(dto, request);
        log.info("[用户登录] 登录成功, 用户名={}, 设备类型={}",
                dto.getUsername(), dto.getDeviceType());
        return Result.ok(loginVO);
    }

    @Operation(summary = "刷新 Token", description = "使用 Refresh Token 刷新 Access Token，无需登录")
    @PostMapping("/refresh")
    public Result<TokenVO> refreshToken(@Valid @RequestBody RefreshTokenDTO dto) {
        log.info("[刷新Token] 执行刷新Token, 方法=refreshToken, 设备类型={}", dto.getDeviceType());
        TokenVO tokenVO = authService.refreshToken(dto);
        log.info("[刷新Token] 刷新Token成功, 设备类型={}", dto.getDeviceType());
        return Result.ok(tokenVO);
    }

    @Operation(summary = "注销当前设备", description = "注销当前设备的登录状态，Token 加入黑名单，需要登录", security = @SecurityRequirement(name = "Authorization"))
    @PostMapping("/logout")
    public Result<Void> logout() {
        Long userId = StpUtil.getLoginIdAsLong();
        String device = (String) StpUtil.getSession().get("device");
        log.info("[用户注销] 用户ID={} 执行注销当前设备, 方法=logout, 设备类型={}", userId, device);
        authService.logout();
        log.info("[用户注销] 用户ID={} 注销当前设备成功, 设备类型={}", userId, device);
        return Result.ok();
    }

    @Operation(summary = "注销所有设备", description = "注销用户在所有设备的登录状态，所有 Token 加入黑名单，需要登录", security = @SecurityRequirement(name = "Authorization"))
    @PostMapping("/logoutAll")
    public Result<Void> logoutAll() {
        Long userId = StpUtil.getLoginIdAsLong();
        log.info("[用户注销] 用户ID={} 执行注销所有设备, 方法=logoutAll", userId);
        authService.logoutAll();
        log.info("[用户注销] 用户ID={} 注销所有设备成功", userId);
        return Result.ok();
    }
}
